package com.huawei.boss.scripts;

import java.io.InputStreamReader;
import java.io.Reader;

import javax.script.Invocable;
import javax.script.ScriptEngine;

import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;

public class ScriptFactoryBean implements InitializingBean, FactoryBean {
    private ScriptEngine engine;
    private Resource scriptsource;
    private String iface;
    private Class<?> iclass;
    private boolean single = true;

    @Override
    public Object getObject() throws Exception {
        Reader reader = new InputStreamReader(scriptsource.getInputStream());
        engine.eval(reader);//解释脚本
        Object obj = ((Invocable) engine).getInterface(iclass);
        reader.close();//TODO exception
        return obj;
    }

    @Override
    public Class getObjectType() {
        return this.iclass;
    }

    @Override
    public boolean isSingleton() {
        return this.single;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        this.iclass = ScriptFactoryBean.class.getClassLoader().loadClass(iface);

        if (!(this.engine instanceof Invocable)) {
            throw new RuntimeException("The engine is not able to invoke functions!");
        }
    }

    public Resource getScriptsource() {
        return scriptsource;
    }

    public void setScriptsource(Resource scriptsource) {
        this.scriptsource = scriptsource;
    }

    public ScriptEngine getEngine() {
        return engine;
    }

    public void setEngine(ScriptEngine engine) {
        this.engine = engine;
    }

    public String getIface() {
        return iface;
    }

    public void setIface(String iface) {
        this.iface = iface;
    }

    public boolean isSingle() {
        return single;
    }

    public void setSingle(boolean single) {
        this.single = single;
    }
}
